package com.sf.dlb.service;

import com.sf.dlb.bean.BzyVideoDataBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.BzyExportRecodInfo;
import com.sf.dlb.jpa.model.BzyOauthInfo;
import com.sf.dlb.jpa.model.NewGetRecodInfo;
import com.sf.dlb.jpa.repository.BzyExportRecodRepository;
import com.sf.dlb.mongo.model.VideoList;
import com.sf.dlb.mongo.repository.VideoListRepository;
import com.sf.dlb.utils.*;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class VideoListService {
    private static Logger logger = LoggerFactory.getLogger(VideoListService.class);

    @Autowired
    private BzyExportRecodRepository bzyExportRecodRepository;
    @Autowired
    private BzyOauthService bzyOauthService;
    @Autowired
    private VideoListRepository videoListRepository;
    @Autowired
    private BzyExportRecodService bzyExportRecodService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Resource
    private Global global;

    /**
     * 获取视频列表
     * @return
     */
    @Transactional
    public ResultVO getVideoList(){
        logger.info("getVideoList start ");
        //1 八爪鱼API授权
        ResultVO resultVO=bzyOauthService.getOauth();
        if(resultVO.getCode()!=200){
            logger.info("getVideoList getOauth is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getVideoList getOauth is null");
        }
        BzyOauthInfo bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
        //删除x小时之前的视频
        deleteBeforeVideo();
        //2 获取任务
        List<BzyExportRecodInfo> bzyExportRecodInfos= bzyExportRecodRepository.findByUsernameAndRemarksAndDelFlag(global.bzy_username,"1","0");
        if(CollectionUtils.isEmpty(bzyExportRecodInfos)){
            logger.info("getVideoList bzyExportRecodInfo is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getVideoList bzyExportRecodInfo is null");
        }
        for (BzyExportRecodInfo bzyExportRecodInfo1:bzyExportRecodInfos) {
            handlerExportData(bzyOauthInfo,bzyExportRecodInfo1);
        }
        logger.info("getVideoList end ");
        return ResultVOUtil.success();
    }
    public void handlerExportData(BzyOauthInfo bzyOauthInfo,BzyExportRecodInfo bzyExportRecodInfo){
        //2.1获取任务记录
        NewGetRecodInfo newGetRecodInfo=new NewGetRecodInfo();
        newGetRecodInfo.setStartTime(new Date());
        newGetRecodInfo.setTaskId(bzyExportRecodInfo.getTaskId());
        //3 根据任务id,偏移量-》获取八爪鱼数据
        String responseBody=bzyExportRecodService.getExportData(bzyOauthInfo,bzyExportRecodInfo);
        BzyVideoDataBean exportDataBean= (BzyVideoDataBean) GsonUtils.getInstance().fromJson(responseBody, BzyVideoDataBean.class);
        newGetRecodInfo.setOffset(bzyExportRecodInfo.getOffset());
        newGetRecodInfo.setSize(bzyExportRecodInfo.getSize());
        if(null==exportDataBean||null==exportDataBean.getData()||CollectionUtils.isEmpty(exportDataBean.getData().getDataList())){
            logger.info("getVideoList null==exportDataBean ");
            bzyExportRecodService.saveGetRecodrs(newGetRecodInfo);
            return;
        }
        List<BzyVideoDataBean.DataBean.DataListBean> exportDataBeans=exportDataBean.getData().getDataList();
        newGetRecodInfo.setGetCount(exportDataBeans.size());
        //3.1 判断数据完整性
        List<BzyVideoDataBean.DataBean.DataListBean> checkDataBeansRepeat=checkVideoData(exportDataBeans);
        newGetRecodInfo.setFilterCount(newGetRecodInfo.getGetCount()-checkDataBeansRepeat.size());
        //4 去重判断
        List<BzyVideoDataBean.DataBean.DataListBean> exportDataBeansRepeat=repeatVideoData(checkDataBeansRepeat);
        newGetRecodInfo.setRepeatCount((newGetRecodInfo.getGetCount()-newGetRecodInfo.getFilterCount())-exportDataBeansRepeat.size());
        //5 列表存储；
        saveVideoData(exportDataBeansRepeat);
        //6 更新下次导数据偏移量；
        bzyExportRecodService.updateExportDataOffset(bzyExportRecodInfo,exportDataBean.getData().getOffset(),exportDataBean.getData().getTotal(),exportDataBean.getData().getRestTotal());
        //7 每次获取数据记录
        bzyExportRecodService.saveGetRecodrs(newGetRecodInfo);
    }
    /**
     * 删除x个小时之前视频
     */
    public void deleteBeforeVideo(){
        //查询出x个小时之前的视频
        Date currentDate60=DateUtils.addSeconds(new Date(),-global.delete_before_video_time);
        Query query =Query.query(Criteria.where("createDate").lt(currentDate60));
        mongoTemplate.remove(query,VideoList.class);
    }
    /**
     * 获取指定任务视频列表
     * @param taskId
     * @return
     */
    public ResultVO getVideoList(String taskId){
        logger.info("getVideoList start taskId={}",taskId);
        //1 八爪鱼API授权；
        ResultVO resultVO=bzyOauthService.getOauth();
        if(resultVO.getCode()!=200){
            logger.info("getVideoList getOauth is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getVideoList getOauth is null");
        }
        BzyOauthInfo bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
        //删除半个月之前的视频
        deleteBeforeVideo();
        //2 获取任务组，任务；
        BzyExportRecodInfo bzyExportRecodInfo= bzyExportRecodRepository.findByTaskIdAndDelFlag(taskId,"0");
        if(null==bzyExportRecodInfo){
            logger.info("getVideoList bzyExportRecodInfo is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getVideoList bzyExportRecodInfo is null");
        }
        handlerExportData(bzyOauthInfo,bzyExportRecodInfo);
        return ResultVOUtil.success();
    }
    /**
     * 校验视频数据完整性
     * @param exportDataBeans
     * @return
     */
    public List checkVideoData(List<BzyVideoDataBean.DataBean.DataListBean> exportDataBeans)
    {
        logger.info("checkVideoData start size "+exportDataBeans.size());
        ArrayList<BzyVideoDataBean.DataBean.DataListBean> checkArray=new ArrayList<>();
        for (BzyVideoDataBean.DataBean.DataListBean dataListBean:exportDataBeans) {
            String title=dataListBean.getTitle();
            String pageUrl=dataListBean.getPageUrl();
            String coverUrl=dataListBean.getCoverUrl();
            String videoLink=dataListBean.getVideoLink();
            String timeLong=dataListBean.getTimeLong();
            int minutes=0;
            if(timeLong.indexOf(":")>0){
                String[] timeLongSplit=timeLong.split(":");
                minutes=Integer.parseInt(timeLongSplit[0]);//大于5分钟的
            }
            if(StringUtils.isBlank(title)||StringUtils.isBlank(coverUrl) ||
                    StringUtils.isBlank(pageUrl) ||StringUtils.isBlank(videoLink)){
                checkArray.add(dataListBean);
            }
        }
        logger.info("checkVideoData checkArray size "+checkArray.size());
        exportDataBeans.removeAll(checkArray);
        logger.info("checkVideoData end size "+exportDataBeans.size());
        return exportDataBeans;
    }
    /**
     * 视频数据去重
     * @param exportDataBeans
     * @return
     */
    public List repeatVideoData(List<BzyVideoDataBean.DataBean.DataListBean> exportDataBeans) {
        logger.info("repeatVideoData start size "+exportDataBeans.size());

        ArrayList<BzyVideoDataBean.DataBean.DataListBean> pageUrlArray=new ArrayList<>();
        for (int i=0;i<exportDataBeans.size();i++) {
            BzyVideoDataBean.DataBean.DataListBean dataListBean=exportDataBeans.get(i);
            //数据库是否有重复的
            String title=dataListBean.getTitle();
            String base64Title=Base64Utils.encodeToString(dataListBean.getTitle().getBytes());
            String coverUrl=dataListBean.getCoverUrl();
            List<VideoList> videoLists = videoListRepository.findByTitleOrCoverUrlAndDelFlag(base64Title,coverUrl,"0");
            if(!CollectionUtils.isEmpty(videoLists)&&videoLists.size()>0){
                pageUrlArray.add(dataListBean);
                continue;
            }
            //当前列表有重复的
            for (int j=(i+1);j<exportDataBeans.size();j++) {
                BzyVideoDataBean.DataBean.DataListBean dataListBean1=exportDataBeans.get(j);
                //数据库是否有重复的
                String title1=dataListBean1.getTitle();
                if(title.equals(title1)){
                    pageUrlArray.add(dataListBean1);
                    continue;
                }
            }
        }

        logger.info("repeatVideoData pageUrlArray size "+pageUrlArray.size());
        exportDataBeans.removeAll(pageUrlArray);
        logger.info("repeatVideoData end size "+exportDataBeans.size());
        return exportDataBeans;
    }

    /**
     * 保存视频数据
     * @param exportDataBeansRepeat
     */
   public void saveVideoData(List<BzyVideoDataBean.DataBean.DataListBean> exportDataBeansRepeat)
    {
        logger.info("saveVideoData start exportDataBeansRepeat.size={}",exportDataBeansRepeat.size());
        for (BzyVideoDataBean.DataBean.DataListBean dataListBean:exportDataBeansRepeat) {
            VideoList videoList=new VideoList();
            BeanUtils.copyProperties(dataListBean,videoList);
            videoList.setTitle(Base64Utils.encodeToString(videoList.getTitle().getBytes()));//标题有特殊字符,如：马蜂窝
            String source=MyStringUtils.stringTrim(dataListBean.getSource());//source有特殊字符,如：马蜂窝
            videoList.setSource(Base64Utils.encodeToString(source.getBytes()));
            videoList.setGrabTime(dataListBean.getCurrentTime());
            //计算播放时长
            int getDlbTime=countDlbTime(dataListBean.getTimeLong());
            videoList.setGetDlbTime(getDlbTime);
            videoList.setCreateDate(new Date());
            videoList.setUpdateDate(new Date());
            videoListRepository.save(videoList);
        }
    }
    /**
     * 计算dlb领取时长
     */
    public int countDlbTime(String timeLong){
        if(StringUtils.isBlank(timeLong)){
            return 0;
        }
        if(timeLong.indexOf(":")<0){
            return 0;
        }
        String[] timelongArray=timeLong.split(":");
        int minutes=Integer.parseInt(timelongArray[0]);//分
        int seconds= Integer.parseInt(timelongArray[1]);//秒
        int dlbTime=(minutes*60+seconds)/2;//观看时长超过视频时长的50%为有效
        return dlbTime;
    }
}
